package com.example.dell.newstart.cart;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.newstart.R;
import com.example.dell.newstart.base.RequestInterface;
import com.example.dell.newstart.base.ServerResponse;
import com.example.dell.newstart.bean.CartList;
import com.example.dell.newstart.bean.CartProduct;
import com.example.dell.newstart.bean.MyApp;
import com.example.dell.newstart.bean.User;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.support.constraint.Constraints.TAG;

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {

    private Activity activity;
    private Context context;
    private float totalPrice = 0;
    private List<CartProduct> mcart = new ArrayList<>();
    static class ViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        ImageView image;
        TextView type;
        TextView price;
        //EditText number1 ;
       CheckBox checkBox;
        private CustomerClickCounter customerClickCounter;
        public ViewHolder(View view) {
            super(view);
            cardView = (CardView) view;
            image = (ImageView) view.findViewById(R.id.image_cart);
            type = (TextView) view.findViewById(R.id.name_cart);
            checkBox = view.findViewById(R.id.part_btn);
            price = view.findViewById(R.id.price);
            customerClickCounter = view.findViewById(R.id.ccc_amount);
        }
    }

    public CartAdapter(Context context) {
        this.context = context;
    }

    //提供一个方法，使得外部Activity 和 Fragment能获取到购物车中商品列表。
    public List<CartProduct> getCartProductList() {
        return mcart;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {//设置上下文环境
            context = parent.getContext();
        }
        View view = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);



         final ViewHolder holder = new ViewHolder(view);
//         holder.item_btn_add.setOnClickListener(new View.OnClickListener() {
//             @Override
//             public void onClick(View v) {
//                 int position = holder.getAdapterPosition();
//               CartProduct cart=mcart.get(position);
//            cart.addNumber();
//            holder.number1.setText(String.valueOf(cart.getQuantity()));
//             }
//         });
//         holder.item_btn_sub.setOnClickListener(new View.OnClickListener() {
//             @Override
//             public void onClick(View v) {
//                 int position = holder.getAdapterPosition();
//                 CartProduct cart = mcart.get(position);
//                 if(cart.getQuantity()==1)
//                 {
//                     Toast.makeText(context,"该商品不能减少了",Toast.LENGTH_SHORT).show();
//                 }
//
//                 else
//                 {
//                     cart.delectNumber();
//                     holder.number1.setText(String.valueOf(cart.getQuantity()));
//                     // notifyItemRangeChanged(position,1);
//                 }
//
//             }
//         });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
      final CartProduct cart = mcart.get(position);
        holder.type.setText(cart.getProductName());
        holder.price.setText(String.valueOf(cart.getProductPrice()));
        Glide.with(context).load(RequestInterface.baseImgPath + cart.getProductMainImage()).into(holder.image);
       holder.customerClickCounter.setMaxNumber(cart.getProductStock());
        Integer number=cart.getQuantity();
       // Log.d(TAG, "onBindViewHolder: number "+number);
//获取购物车数量
      holder.customerClickCounter.setNumber(number);


       holder.checkBox.setOnCheckedChangeListener(null);//避免布局复用产生的bug
       //holder.customerClickCounter.setNumber(cart.getQuantity());
        holder.checkBox.setChecked(cart.getProductChecked() != null && cart.getProductChecked() != 1);
//规定1为没有选中
        //购物车中商品被选中与否的逻辑
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO: 2018/12/30 执行购物车中商品没有被勾选逻辑
                if(isChecked)
                {
                    cart.setProductChecked(0);
                    if (onPriceChangeListener != null) {
                        onPriceChangeListener.priceChange();
                    }
                }
                else{
                    cart.setProductChecked(1);
                    if (onPriceChangeListener != null) {
                        onPriceChangeListener.priceChange();
                    }
                }

            }
        });

        //购物车商品数量变化的监听
        holder.customerClickCounter.setOnNumberChangeListener(new CustomerClickCounter.OnNumberChangeListener() {
            //数量增减器数量发生变化时候执行
            @Override
            public void onNumberChange(int number) {
                cart.setQuantity(number);
                updateCartProductListRequest(cart.getProductId(),number);
                // TODO: 2018/12/30 和后台联动，改变商品数量 ，此处我们不实时改变商品数量
                if (cart.getProductChecked() == 1) {//如果没有被选中，则价格不会变化（终止）
                    return;
                }
                if (onPriceChangeListener != null) {
                    onPriceChangeListener.priceChange();//触发价钱变化接口

                }
            }
        });

        //长按删除逻辑
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showDeleteCartProductAlert(position);
                // TODO: 2018/12/30  调用后台接口，完成删除逻辑
                return false;
            }
        });

    }


    @Override
    public int getItemCount() {
        return mcart.size();
    }





    //获取选中item
    public List<CartProduct> getSelectedItemList() {
        List<CartProduct> selectedItemList = new ArrayList<>();
        for (CartProduct orderItem : mcart) {
            if (orderItem.getProductChecked() == 0) {
                selectedItemList.add(orderItem);
            }
        }
        return selectedItemList;
    }


    //全选或者取消全选逻辑
    public void setSelectedOrderItemList(boolean selectedAll) {
        for (CartProduct cartProduct : mcart) {
            cartProduct.setProductChecked(selectedAll ? 0 : 1);
            Log.d(TAG, "setSelectedOrderItemList: _________________________" + cartProduct.toString());
        }
        notifyDataSetChanged();
        if (onPriceChangeListener != null) {
            onPriceChangeListener.priceChange();
        }
    }

    //商品价钱变化的接口 该接口逻辑可能在 商品数量发生变化、商品是否被勾选、全选（取消）时候被触发
    public interface OnPriceChangeListener {
        void priceChange();
    }

    private OnPriceChangeListener onPriceChangeListener;

    public void setOnPriceChangeListener(OnPriceChangeListener onPriceChangeListener) {
        this.onPriceChangeListener = onPriceChangeListener;
    }


    //购物车中没有 商品时候，通知UI显示没有商品的视图
    public interface OnCartVisibilityChangeListener {
        void onVisibilityChange(boolean visible);
    }

    private OnCartVisibilityChangeListener onCartVisibilityChangeListener;

    public void setOnCartVisibilityChangeListener(OnCartVisibilityChangeListener onCartVisibilityChangeListener) {
        this.onCartVisibilityChangeListener = onCartVisibilityChangeListener;
    }


//长按删除逻辑
private void showDeleteCartProductAlert(final int position) {
    new AlertDialog.Builder(context)
            .setTitle("删除商品")
            .setNegativeButton("我再想想", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setPositiveButton("确定删除", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mcart.remove(position);
                    delectCartProductListRequest(mcart.get(position).getProductId());
                    if (mcart.size() == 0) {
                        /**
                         * 没有商品，购物车为空，通知UI显示空购物车
                         */
                        if (onCartVisibilityChangeListener != null) {
                            onCartVisibilityChangeListener.onVisibilityChange(false);
                        }
                    }
                    notifyDataSetChanged();
                }
            })
            .create()
            .show();
}

    //获取所有选中项的总价
    public float getTotalPrice() {
        totalPrice = 0;
        for (CartProduct product : getSelectedItemList()) {
            float price = product.getProductPrice().floatValue();
            int amount = product.getQuantity();
            totalPrice = price * amount + totalPrice;
            Log.d(TAG, " %%%%%%%%%%%%%%%%%" + " 当前总价 " + totalPrice
                    + " 单价 " + price + " 数量 "
                    + amount + "\n" + " 商品 " + product.toString());
        }
        return totalPrice;
    }


    //加载数据
    public void loadData() {
        sendCartProductListRequest();
    }

    private void toastShort(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }




    //获取购物车数据
    private void sendCartProductListRequest() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Cart requestInterfaceLogin = retrofit.create(RequestInterface.Cart.class);
        User user2 = MyApp.getCurrentUser();
        if (user2   == null) {
            Toast.makeText(context, "请先登陆", Toast.LENGTH_SHORT).show();
            //context.startActivity(new Intent(context, LoginActivity.class));
            return;
        }
        Call<ServerResponse<CartList>> call = requestInterfaceLogin.getCartList(user2.getId());

        call.enqueue(new Callback<ServerResponse<CartList>>() {

            @Override
            public void onResponse(Call<ServerResponse<CartList>> call, Response<ServerResponse<CartList>> response) {
                /**
                 * response.body()获取到返回的ServerResponse，再通过获取Status判断是否
                 * 登陆成功/请求数据成功
                 */
                if (response.body() == null) {
                    toastShort("未获取到相关数据");
                    return;
                }
                //log(response.body().getMsg());
                if (response.body().getStatus() == 0) {
                    //获取返回的数据（就是泛型ServerResponse中的T所代表的数据）
                    CartList cartList = response.body().getData();
                    if (cartList != null) {
                        List<CartProduct> cartProductList = cartList.getCartProductVoList();
                        if (cartProductList != null && cartProductList.size() > 0) {
                           // mcart.clear();
                            mcart.addAll(cartProductList);//更新适配器数据
                            notifyDataSetChanged();//通知变化
                            if (onCartVisibilityChangeListener != null) {
                                onCartVisibilityChangeListener.onVisibilityChange(true);
                            }
                        } else {
                            if (onCartVisibilityChangeListener != null) {
                                onCartVisibilityChangeListener.onVisibilityChange(false);
                            }
                        }
                    }
                } else {
                    toastShort("未获取到相关数据");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<CartList>> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
                toastShort("获取相关数据失败！");
            }
        });
    }






    //修改购物车商品数量
    private void updateCartProductListRequest(int product,int count) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Cart requestInterfaceLogin = retrofit.create(RequestInterface.Cart.class);
        User user2 = MyApp.getCurrentUser();
        if (user2   == null) {
            Toast.makeText(context, "请先登陆", Toast.LENGTH_SHORT).show();
            //context.startActivity(new Intent(context, LoginActivity.class));
            return;
        }
        Call<ServerResponse<CartList>> call = requestInterfaceLogin.update(product,count,user2.getId());

        call.enqueue(new Callback<ServerResponse<CartList>>() {

            @Override
            public void onResponse(Call<ServerResponse<CartList>> call, Response<ServerResponse<CartList>> response) {
                /**
                 * response.body()获取到返回的ServerResponse，再通过获取Status判断是否
                 * 登陆成功/请求数据成功
                 */
                if (response.body() == null) {
                    toastShort("未获取到相关数据");
                    return;
                }
                //log(response.body().getMsg());
                if (response.body().getStatus() == 0) {
                    //获取返回的数据（就是泛型ServerResponse中的T所代表的数据）
//                    CartList cartList = response.body().getData();
//                    if (cartList != null) {
//                        List<CartProduct> cartProductList = cartList.getCartProductVoList();
//                        if (cartProductList != null && cartProductList.size() > 0) {
//                          mcart.clear();
//                            mcart.addAll(cartProductList);//更新适配器数据
//                            notifyDataSetChanged();//通知变化
//                            if (onCartVisibilityChangeListener != null) {
//                                onCartVisibilityChangeListener.onVisibilityChange(true);
//                            }
//                        } else {
//                            if (onCartVisibilityChangeListener != null) {
//                                onCartVisibilityChangeListener.onVisibilityChange(false);
//                            }
//                        }
//                    }
                } else {
                    toastShort("修改失败！");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<CartList>> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
                toastShort("获取相关数据失败！");
            }
        });
    }




    //删除购物车商品
    private void delectCartProductListRequest(int product) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.Cart requestInterfaceLogin = retrofit.create(RequestInterface.Cart.class);
        User user2 = MyApp.getCurrentUser();
        if (user2   == null) {
            Toast.makeText(context, "请先登陆", Toast.LENGTH_SHORT).show();
            //context.startActivity(new Intent(context, LoginActivity.class));
            return;
        }
        Call<ServerResponse<CartList>> call = requestInterfaceLogin.delete(product,user2.getId());

        call.enqueue(new Callback<ServerResponse<CartList>>() {

            @Override
            public void onResponse(Call<ServerResponse<CartList>> call, Response<ServerResponse<CartList>> response) {
                /**
                 * response.body()获取到返回的ServerResponse，再通过获取Status判断是否
                 * 登陆成功/请求数据成功
                 */
                if (response.body() == null) {
                    toastShort("未获取到相关数据");
                    return;
                }
                //log(response.body().getMsg());
                if (response.body().getStatus() == 0) {
                    //获取返回的数据（就是泛型ServerResponse中的T所代表的数据）
//                    CartList cartList = response.body().getData();
//                    if (cartList != null) {
//                        List<CartProduct> cartProductList = cartList.getCartProductVoList();
//                        if (cartProductList != null && cartProductList.size() > 0) {
//                             mcart.clear();
//                            mcart.addAll(cartProductList);//更新适配器数据
//                            notifyDataSetChanged();//通知变化
//                            if (onCartVisibilityChangeListener != null) {
//                                onCartVisibilityChangeListener.onVisibilityChange(true);
//                            }
//                        } else {
//                            if (onCartVisibilityChangeListener != null) {
//                                onCartVisibilityChangeListener.onVisibilityChange(false);
//                            }
//                        }
//                    }
                } else {
                    toastShort("删除错误");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<CartList>> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.getMessage());
                toastShort("获取相关数据失败！");
            }
        });
    }

}



